﻿using DTOs;
using RBAC.Domain.Service.Interfae;
using RBAC.Repository.Impl;
using RBAC.Repository.Interfae;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace RBAC.Domain.Service.Impl
{
    public class UserServices : IUserService
    {
        /// <summary>
        /// 用户仓储
        /// </summary>
        protected readonly IUserRepository _userService;
        /// <summary>
        /// 省份仓储
        /// </summary>
        protected readonly IProvinceRepository _provinceService;
        /// <summary>
        /// 市仓储
        /// </summary>
        protected readonly ICityRepository _cityService;
        /// <summary>
        /// 县仓储
        /// </summary>
        protected readonly ICountryRepository _countryService;
        /// <summary>
        /// 角色仓储
        /// </summary>
        protected readonly IRoleRepository _roleService;
        /// <summary>
        /// 用户与角色仓储
        /// </summary>
        protected readonly IUserRoleRepository _UserRoleService;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userService"></param>
        public UserServices(IUserRepository userService, IProvinceRepository provinceService,
            ICityRepository cityService, ICountryRepository countryService, IRoleRepository roleService,
            IUserRoleRepository UserRoleService)
        {
            _userService = userService;
            _provinceService = provinceService;
            _cityService = cityService;
            _countryService = countryService;
            _roleService = roleService;
            _UserRoleService = UserRoleService;
        }



        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public async Task<int> AddUser(UserInfo userInfo)
        {
            //判断唯一性
            var useradd = await _userService.GetAsync(d => d.userName == userInfo.userName);
            if(useradd.Count() > 0)
            {
                return -1;
            }
return await _userService.AddAsync(userInfo);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> DelUser(int id)
        {
            var del = await _userService.GetModelsAsync(id);
            del.IsDel = true;
            del.delName = "王器";
            del.delDate = DateTime.Now;
            return await _userService.UpdateAsync(del);
        }
        /// <summary>
        /// 显示全部
        /// </summary>
        /// <returns></returns>
        public async Task<PageDto<UserDto>> GetAll(int pageSize,int pageIndex)
        {
            PageDto<UserDto> pageDto = new PageDto<UserDto>();
            var listobj = (from a in await _userService.GetAllAsync()
                            join b in await _provinceService.GetAllAsync()
                            on a.provinceId equals b.provinceId
                            join c in await _cityService.GetAllAsync()
                            on a.cityId equals c.cityId
                            join d in await _countryService.GetAllAsync()
                            on a.countryId equals d.countryId
                            where !a.IsDel
                            select new UserDto
                            {
                                userInfoId = a.userInfoId,
                                userInfoName = a.userInfoName,
                                password = a.password,
                                userName = a.userName,
                                userSex = a.userSex,
                                provinceId = a.provinceId,
                                cityId = a.cityId,
                                countryId = a.countryId,
                                userAddress = a.userAddress,
                                IsDel = a.IsDel,
                                provinceName = b.provinceName,
                                cityName = c.cityName,
                                countryName = d.countryName,
                                addName = a.addName,
                                addDate = a.addDate,
                                updateName = a.updateName,
                                updateDate = a.updateDate,
                                departmentId = a.departmentId,


                            });

            pageDto.ToalCount = listobj.Count();
            pageDto.PageCount = (int)Math.Ceiling(listobj.Count() * 1.0 / pageSize);
            pageDto.list = listobj.OrderByDescending(d => d.addDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return pageDto;
          


        }
        /// <summary>
        /// 显示全部
        /// </summary>
        /// <returns></returns>
        public async Task<List<UserInfo>> Getall()
        {
            return await _userService.GetAllAsync();
        }



        /// <summary>
        /// 反填用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        public async Task<UserInfo> GetUserAll(UserInfo userInfo)
        {
            return await _userService.GetModelsAsync(userInfo.userInfoId);
        }
        /// <summary>
        /// 反填（从Token中取用户ID）1
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<UserInfo> GetUserAlls(int id)
        {
            return await _userService.GetModelsAsync(id);
        }
        /// <summary>
        /// 反填（从Token中取用户ID）2
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<List<UserInfo>> GetUserFill(int uid)
        {
            return await _userService.GetAsync(d => d.userInfoId != uid);
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="Uname"></param>
        /// <param name="Upwd"></param>
        /// <returns></returns>
        public async Task<LoginDto> Logain(string Uname, string Upwd)
        {
            // 实例化返回值
            LoginDto login = new LoginDto();

            // 获取所有用户信息
            var list = await _userService.GetAllAsync();

            // 查找匹配的用户
            login.Userinfos = list.FirstOrDefault(d => d.userInfoName == Uname && d.password == Upwd);

            if (login.Userinfos == null)
            {
                return null; // 用户不存在或密码不匹配
            }

            // 查询角色ID
            var blist = await _UserRoleService.GetAsync(d => d.userInfoId == login.Userinfos.userInfoId);

            // 存储角色ID
            var roleIds = blist.Select(item => item.roleId).Distinct().ToList();

            // 转成字符串
            //login.roleId = string.Join(",", roleIds);

            return login;

            // //实例化返回值
            // LoginDto login = new LoginDto();
            // var list=await _userService.GetAllAsync();
            // login.Userinfos = list.Find(d => d.userInfoName == Uname && d.password == Upwd);

            // //if(list.Count == 0)
            // //{
            // //    return null;
            // //}
            //// 查询角色ID
            // var blist = await _UserRoleService.GetAsync(d => d.userInfoId == login.Userinfos.userInfoId);
            // var array = new List<int>();
            // foreach (var item in blist)
            // {
            //     //存角色ID
            //     array.Add(item.roleId);
            // }
            // //转成字符串
            // login.roleId = string.Join(",", array);
            // return login;


            //var login = await _userService.GetAsync(d => d.userInfoName == Uname&&d.password==Upwd&&!d.IsDel);
            //if (login==null)
            //{
            //    return null;
            //}
            //else
            //{
            //    return login.FirstOrDefault();
            //}



        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>

        public async Task<int> UpdateUserInfo(UserInfo userInfo)
        {
            
            userInfo.updateName = "王宏";
            userInfo.updateDate = DateTime.Now;
            return await _userService.UpdateAsync(userInfo);
          
        }
        /// <summary>
        /// 显示全部
        /// </summary>
        /// <returns></returns>
        public async Task<List<UserInfo>> Getalls()
        {
            return await _userService.GetAllAsync();
        }
    }
}
